<script setup lang="ts">
import { nextTick, onMounted, ref } from 'vue'

// 用户信息
const userInfo = ref({
  id: 1,
  username: '我',
  avatar: '/static/images/avatar/default.svg',
})

// 目标用户信息
const targetInfo = ref({
  id: 2,
  username: '张三',
  avatar: '/static/images/avatar/default.svg',
})

// 消息列表
const messages = ref([
  {
    id: 1,
    content: '你好，我想借阅《三体》这本书',
    createTime: '2025-03-15 14:30:00',
    isMine: false,
  },
  {
    id: 2,
    content: '好的，这本书目前可以借阅',
    createTime: '2025-03-15 14:31:00',
    isMine: true,
  },
  {
    id: 3,
    content: '请问什么时候可以见面交接？',
    createTime: '2025-03-15 14:32:00',
    isMine: false,
  },
])

// 输入框内容
const inputContent = ref('')

// 是否还有更多数据
const hasMore = ref(true)

// 页码
const page = ref(1)

// 滚动位置
const scrollTop = ref(0)

// 格式化时间
function formatTime(time: string) {
  const date = new Date(time)
  const now = new Date()
  const diff = now.getTime() - date.getTime()

  // 今天
  if (diff < 24 * 60 * 60 * 1000) {
    return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
  }

  // 昨天
  if (diff < 48 * 60 * 60 * 1000) {
    return `昨天 ${date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })}`
  }

  // 一周内
  if (diff < 7 * 24 * 60 * 60 * 1000) {
    const days = ['日', '一', '二', '三', '四', '五', '六']
    return `星期${days[date.getDay()]} ${date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })}`
  }

  // 更早
  return `${date.toLocaleDateString('zh-CN', { month: '2-digit', day: '2-digit' })} ${
    date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })}`
}

// 是否显示时间分割线
function showTimeDivider(index: number) {
  if (index === 0)
    return true

  const current = new Date(messages.value[index].createTime)
  const previous = new Date(messages.value[index - 1].createTime)

  return current.getTime() - previous.getTime() > 5 * 60 * 1000 // 5分钟
}

// 发送消息
async function sendMessage() {
  if (!inputContent.value.trim())
    return

  try {
    // TODO: 调用发送消息API
    // await sendMessage({
    //   targetId: targetInfo.value.id,
    //   content: inputContent.value
    // });

    // 添加消息到列表
    messages.value.push({
      id: Date.now(),
      content: inputContent.value,
      createTime: new Date().toISOString(),
      isMine: true,
    })

    // 清空输入框
    inputContent.value = ''

    // 滚动到底部
    await nextTick()
    scrollToBottom()
  }
  catch (error) {
    uni.showToast({
      title: '发送失败',
      icon: 'none',
    })
  }
}

// 加载更多消息
async function loadMore() {
  if (!hasMore.value)
    return

  try {
    // TODO: 调用获取消息API
    // const res = await getMessages({
    //   targetId: targetInfo.value.id,
    //   page: page.value
    // });
    // messages.value = [...res.data, ...messages.value];
    // hasMore.value = res.data.length === 10;
    // page.value++;
  }
  catch (error) {
    uni.showToast({
      title: '加载失败',
      icon: 'none',
    })
  }
}

// 滚动到底部
function scrollToBottom() {
  const query = uni.createSelectorQuery()
  query.select('.chat-list').boundingClientRect()
  query.exec((res) => {
    if (res[0]) {
      scrollTop.value = res[0].height
    }
  })
}

// 获取聊天记录
async function getChatHistory() {
  try {
    // TODO: 调用API获取数据
    // const res = await getChatHistory({
    //   targetId: targetInfo.value.id,
    //   page: page.value
    // });
    // messages.value = res.data;
    // hasMore.value = res.data.length === 10;

    // 滚动到底部
    await nextTick()
    scrollToBottom()
  }
  catch (error) {
    uni.showToast({
      title: '加载失败',
      icon: 'none',
    })
  }
}

// 页面加载时获取数据
onMounted(() => {
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1]
  const id = currentPage.$page?.options?.id
  if (id) {
    // TODO: 获取目标用户信息
    // getTargetInfo(id);
    getChatHistory()
  }
})
</script>

<template>
  <view class="container">
    <!-- 聊天记录 -->
    <scroll-view
      class="chat-list"
      scroll-y
      :scroll-top="scrollTop"
      @scrolltoupper="loadMore"
    >
      <!-- 加载更多 -->
      <view v-if="hasMore" class="load-more">
        <text>加载更多</text>
      </view>

      <!-- 消息列表 -->
      <view class="message-list">
        <view
          v-for="(item, index) in messages"
          :key="index"
          class="message-item"
          :class="{ 'message-mine': item.isMine }"
        >
          <!-- 时间分割线 -->
          <view v-if="showTimeDivider(index)" class="time-divider">
            <text>{{ formatTime(item.createTime) }}</text>
          </view>

          <!-- 消息内容 -->
          <view class="message-content">
            <image
              class="avatar"
              :src="item.isMine ? userInfo.avatar : targetInfo.avatar"
              mode="aspectFill"
            />

            <view class="message-bubble">
              <text>{{ item.content }}</text>
            </view>
          </view>
        </view>
      </view>
    </scroll-view>

    <!-- 输入框 -->
    <view class="input-box">
      <view class="input-area">
        <input
          v-model="inputContent"
          type="text"
          placeholder="请输入消息"
          confirm-type="send"
          @confirm="sendMessage"
        >
      </view>

      <view class="send-btn" @click="sendMessage">
        <text>发送</text>
      </view>
    </view>
  </view>
</template>

<style lang="scss">
.container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: #f5f5f5;
}

.chat-list {
  flex: 1;
  padding: 20rpx;

  .load-more {
    text-align: center;
    padding: 20rpx 0;
    color: #999;
    font-size: 24rpx;
  }

  .message-list {
    .message-item {
      margin-bottom: 30rpx;

      .time-divider {
        text-align: center;
        margin: 20rpx 0;

        text {
          display: inline-block;
          padding: 4rpx 16rpx;
          background: rgba(0, 0, 0, 0.1);
          border-radius: 8rpx;
          font-size: 24rpx;
          color: #666;
        }
      }

      .message-content {
        display: flex;
        align-items: flex-start;

        .avatar {
          width: 80rpx;
          height: 80rpx;
          border-radius: 50%;
          margin: 0 20rpx;
        }

        .message-bubble {
          max-width: 60%;
          padding: 20rpx;
          background: #fff;
          border-radius: 12rpx;
          font-size: 28rpx;
          color: #333;
          line-height: 1.6;
          word-break: break-all;
        }
      }

      &.message-mine {
        .message-content {
          flex-direction: row-reverse;

          .message-bubble {
            background: #4caf50;
            color: #fff;
          }
        }
      }
    }
  }
}

.input-box {
  display: flex;
  align-items: center;
  padding: 20rpx;
  background: #fff;
  border-top: 1rpx solid #eee;

  .input-area {
    flex: 1;
    margin-right: 20rpx;

    input {
      width: 100%;
      height: 80rpx;
      background: #f5f5f5;
      border-radius: 40rpx;
      padding: 0 30rpx;
      font-size: 28rpx;
    }
  }

  .send-btn {
    width: 120rpx;
    height: 80rpx;
    line-height: 80rpx;
    text-align: center;
    background: #4caf50;
    color: #fff;
    font-size: 28rpx;
    border-radius: 40rpx;
  }
}
</style>
